package com.woniuxy.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.woniuxy.gateway.util.Jwtutil;
import org.joda.time.DateTime;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/9 0009-下午 7:53
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER-1;//发送响应之前执行
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String uri = request.getRequestURI();
        if(uri.endsWith("/subLogin")){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //生成一个token，将token响应给客户端，添加到响应头
        RequestContext context = RequestContext.getCurrentContext();
        //获取响应流对象
        InputStream inputStream = context.getResponseDataStream();
         try {
             String responseBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
             System.out.println("responseBody:"+responseBody);
             ObjectMapper objectMapper = new ObjectMapper();
             //利用此方法可以将json格式的字符串解析成对象
             Map res = objectMapper.readValue(responseBody,Map.class);
             Map claims = new HashMap();
             claims.put("uname",(String)res.get("data"));
             //生成token
             Date expireDate = DateTime.now().plusDays(2).toDate();
             String token = Jwtutil.createToken(expireDate,claims);
//             String token = "token001";
             context.getResponse().addHeader("Access-Control-Expose-Headers","token");
             context.getResponse().addHeader("token",token);
             context.setSendZuulResponse(true);
             //将响应体中的数据写到响应中
             context.setResponseBody(responseBody);
         } catch (IOException e) {
             e.printStackTrace();
         }
        return null;
    }
}
